<#
    .AUTHOR
        cw50406@imcnam.ssmb.com  
    .GROUP
        RPA AA STE Support Team(dl.gt.cn.cstc.rpa.aa.ste@imcnam.ssmb.com)
    .VERSION
        2.0
    .Synopsis
        Remote VDI folder/files cleanup trigger with Task scheduler
    .DESCRIPTION
        This script is used to trigger cleanup.ps1 by specified different parames with scheduled task created in aaadmin user session.
    .EXAMPLE
        .\master.ps1 -vdi_source txt -inputFileSaved
        The script will trigger cleanup.ps1 with vdi and fid list from vdi_fid_list.txt in the same directory and then clean all the temp folder as default
    .EXAMPLE
        .\master.ps1 -vdi_source db
        The script will trigger cleanup.ps1 with vdi and fid list from db depening on the script running computer domain and then clean all the temp folder as default
    .EXAMPLE
        .\master.ps1 -vdi_source db -clean_path "C:\Temp\test"
        The script will trigger cleanup.ps1 with vdi and fid list from db depening on the script running computer domain and then clean all the files in "C:\Temp\test" folder
#>
[CmdletBinding()]param(
    [Parameter(Mandatory=$false)]
    [ValidateSet("db","txt","csv")]
    [string]$vdi_source="db",                                  # where the script will get the VDI-FID list
    [ValidateSet('prod','uat','dev','poc','lab')]
    [string]$vdi_env="uat",                                    # which env the script will take actions on the vdis
    [string]$input_file="vdi_fid_list.txt",                    # used when $vdi_source is not 'db'
    [string]$clean_path="C:\Users\#fid\AppData\Local\Temp",    # the path to be cleaned up, will be replaced to be the absolute path when running
    [switch]$inputFileSaved                                    # whether the $input_file has already been saved
)
$this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition)
. "$this_path\functions.ps1"  #<-------------------------------- initilize parames, functions & .NET assembles
Write-Log Normal "--------------------------------START OF SCRIPT---------------------------------" $log_file
If( (query user aaadmin 2>$null)){ # the main task will only be ran in active aaadmin user session
    Write-Log Success "User aaadmin has already logged in $this_machine" $log_file
}else{
    try{ 
        write-log Normal "Trying to get aaadmin password for VM login" $log_file
        If( ($rdc_login_user_pwd=[CredentialValidate.GetPassword]::ReturnLoginPWD()) -eq $null ){
            Stop-WithError "Not get aaadmin password!" $vdi_env
        }elseif(! (Validate-Credential "nam\aaadmin" $rdc_login_user_pwd $log_file )){
            Stop-WithError "Invalid aaadmin password: $rdc_login_user_pwd !" $vdi_env
        }
        write-log Normal 'Trying to remove login ok button' $log_file # cause no person will click it
        reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system\" /v legalnoticecaption /f 2>$null
        reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system\" /v legalnoticetext /f 2>$null
        cmdkey.exe /generic:$this_machine /user:nam\aaadmin /pass:$rdc_login_user_pwd 1>$null 2>&1
    }catch{Write-Log Error $_ $log_file}
    try{
        mstsc.exe /v $this_machine 1>$null 2>&1 ; $loop_cnt=0
        Do{ # loop to find if aaadmin has logged in $this_machine
            sleep 5
            If( $loop_cnt++ -gt 59 ){
                Stop-WithError "not found aaadmin loged in this machine after 5 mins" $vdi_env
            }
        }While([string]::IsNullOrWhiteSpace((query user aaadmin 2>$null)))
        Write-Log Success "User $rdc_login_user has now logged in $this_machine" $log_file
    }catch{Stop-WithError "Unhandled Error:$_" $vdi_env}
}
write-log Normal "Adding VM login user(aaadmin) write access to autosys log file" $log_file
$log_file,$autosys_out_log,$this_path |%{Set-FileAccess $_ "nam\aaadmin"}
If( New-ScheduledTask 'cleanup' -task_arg "-WindowStyle Hidden -Executionpolicy unrestricted `"$this_path\cleanup.ps1 $vdi_source $vdi_env `'$clean_path`' `'$input_file`' `'$log_file`'`"" -run_task_user 'nam\aaadmin' -run_login_only ){ # if task has been created 
    If( SCHTASKS /QUERY /TN 'cleanup' 2>$null ){ # if task has been found 
        SCHTASKS /run /TN 'cleanup' 1>$null 2>&1 ; $loop_cnt=1
        $cpu_cores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors
        $max_cpu_usage,$max_memory_usage=Get-ProcessUsage $cpu_cores $max_cpu_usage $max_memory_usage $log_file
        Do{
            If( (SCHTASKS /QUERY /TN 'cleanup' 2>$null) -imatch "Ready" ){ # if task has been found ready (which means it finished running)
                break
            }
            If( ($loop_cnt % 10) -eq 0){ # send warning email every 10 minutes  # cw50406@imcnam.ssmb.com  dl.gt.cn.cstc.rpa.aa.ste@imcnam.ssmb.com
                Send-MailMessage `
                    -From ("aaadmin."+$this_machine+"@imcnam.ssmb.com") `
                    -To dl.gt.cn.cstc.rpa.aa.ste@imcnam.ssmb.com `
                    -Subject ("[{0}-$this_domain-VDI] RPA AA STE VDI Cleanup - Warning" -f $vdi_env.toupper()) `
                    -Body "Hi RPA AA STE Support, `n`nVDI Cleanup is still running in $this_domain VDIs after $loop_cnt mins.`n`nPlease check details in the attached log. `n`nThank You! `n`nAAADMIN" `
                    -Attachments $log_file `
                    -SmtpServer "imta.citicorp.com" -Port 25 `
                    -Encoding([System.Text.Encoding]::UTF8) -ea 1
            }
            If( $loop_cnt++ -gt 300){ # quit script if running time more than 5 hour 
                $max_cpu_usage,$max_memory_usage=Get-ProcessUsage $cpu_cores $max_cpu_usage $max_memory_usage $log_file ; break
            }sleep 60
            $max_cpu_usage,$max_memory_usage=Get-ProcessUsage $cpu_cores $max_cpu_usage $max_memory_usage $log_file
        }While( $true )
        write-log Normal ("Powershell Running Maximum Usage: CPU(%)-{0} Memory(KB)-{1}" -f $max_cpu_usage,$max_memory_usage) $log_file
        Export-LogToAutosys $log_file "C:\Program Files\CA\Workload Automation AE\SystemAgent\WA1_AGENT\log\VDICleanup\out.log"
        If( test-path $folder_size_file -ea 0 ){$attached_files=@($log_file,$folder_size_file)}else{$attached_files=@($log_file)}
        Send-Mailtoteam "SUCCESS" $vdi_env.toupper() $attached_files
    }
    SCHTASKS /delete /TN 'cleanup' /F 1>$null 2>&1
}
